<!--
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->


<dom-module id="shop-product-detail">

    <template>

    <style include="shop-common-styles shop-button shop-select">

      :host {
        display: block;
      }

      #content {
        @apply --layout-horizontal;
        @apply --layout-center-justified;
      }

      shop-image {
        position: relative;
        margin: 64px 32px;
        width: 50%;
        max-width: 600px;
        --shop-image-img: {
          @apply --layout-fit;
        };
      }

      shop-image::before {
        content: "";
        display: block;
        padding-top: 100%;
      }

      .detail {
        margin: 64px 32px;
        width: 50%;
        max-width: 400px;
        transition: opacity 0.4s;
        opacity: 0;
      }

      .detail[has-content] {
        opacity: 1;
      }

      h1 {
        font-size: 24px;
        font-weight: 500;
        line-height: 28px;
        margin: 0;
      }

      .price {
        margin: 16px 0 40px;
        font-size: 16px;
        color: var(--app-secondary-color);
      }

      .description {
        margin: 32px 0;
      }

      .description > h2 {
        margin: 16px 0;
        font-size: 13px;
      }

      .description > p {
        margin: 0;
        color: var(--app-secondary-color);
      }

      .pickers {
        @apply --layout-vertical;
        border-top: 1px solid #ccc;
      }

      shop-select > select {
        font-size: 16px;
        padding: 16px 24px 16px 70px;
      }

      @media (max-width: 767px) {

        #content {
          @apply --layout-vertical;
          @apply --layout-center;
        }

        shop-image {
          margin: 0;
          width: 80%;
        }

        .detail {
          box-sizing: border-box;
          margin: 32px 0;
          padding: 0 24px;
          width: 100%;
          max-width: 600px;
        }

        h1 {
          font-size: 20px;
          line-height: 24px;
        }

        .price {
          font-size: inherit;
          margin: 12px 0 32px;
        }
      }
        
        .sku-option{
            display: grid;
            grid-template-columns: 50px auto;
            align-items: center;
        }
        paper-listbox{
            display: flex;
            flex-direction: row;
        }
        paper-item{
            font-size: 13px;
            border: #ddd solid 1px;
            margin: auto 1px;
            flex: 1;
            display: flex;
            justify-content: center;
            --paper-item-min-height:30px;
            padding:0px;
            --paper-item-focused-before:{background-color: #ddd}
        }
        paper-item.iron-selected{
            background-color: #ddd;
            color: #000;
        }
        plugin-scroll-box img{
            width:100%;
        }
        .medias{
            position: relative;
            display: block;
            width: 100%;
            height: auto;
        }
        .medias paper-icon-button{
            position: absolute;
            right: 10px;
            bottom: 0px;
            background-color: rgba(0,0,0,0.5);
            z-index: 1;
            border-radius: 50%;
            color: #fff;
        }
        #videoContainer .closeButton{
            position: absolute;
            width: 100%;
            height: 50px;
            left: 0px;
            bottom: 0px;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #000;
            color: #fff;
            padding: 0px;
            margin: 0px;
        }
        .action{
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
            position: fixed;
            left: 0px;
            bottom: 0px;
            z-index: 1;
        }
        .action shop-button[responsive]{
            flex: 1;
            position: static;
        }
        .action shop-button:first-of-type button {
            background-color: #006699;
        }
        .plugins{
            position: fixed;
            right: 0px;
            top: 0px;
            height: 100%;
            display: flex;
            align-items: flex-end;
            justify-content: center;
            flex-direction: column;
            z-index: 2;
            width: 1px;
        }
        .plugins .warp{
            background-color: rgba(0,0,0,0.5);
            padding: 5px;
        }
        .plugins .plugin{
            color: #fff;
            font-size: 12px;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            margin: 3px 0px;
        }
        .plugins img{
            width: 60px;
            height: 60px;
            object-fit: cover;
        }
        s{
            color: #999;
        }
    </style>
    <paper-dialog id="videoContainer" style="position: fixed;padding: 0px;margin: 0px;max-width:100%;max-height: 100%; width: 100%;height: 100%;left: 0px;top: 0px;" on-iron-overlay-closed="_closeVideo">
        <div style="top:0px;bottom: 50px;position: absolute;padding: 0px;margin: 0px;padding: 0px;margin: 0px;background-color: #000;">
        <video id="video" style="width:100%;height:100%;" id="videoPlayer" playsinline x5-playsinline webkit-playsinline controls></video>
        </div>
        <div class="closeButton" dialog-dismiss>
            关闭
        </div>
    </paper-dialog>
    
    <plugin-xhr id="xhr_plugin_list_by_category_point" url="[[app.apiHost]]/plugin.list.by.category.point.product.bind" response="{{plugins}}" response-property="result"></plugin-xhr>
    <plugin-xhr id="xhr_open_page" url="[[app.apiHost]]/wx.app.call?name=openPage"></plugin-xhr>
    <plugin-xhr id="xhr_product" url="[[app.apiHost]]/product.get" response="{{product}}"></plugin-xhr>
    <plugin-xhr id="xhr_promotion_onetoone_get" url="[[app.apiHost]]/promotion.onetoone.get" response="{{promotions}}"></plugin-xhr>
    <plugin-message id="msg"></plugin-message>
    <!--
      app-route provides the name of the category and the item.
    -->
    <app-route
        route="[[route]]"
        pattern="/:product_id"
        data="{{routeData}}"></app-route>
    <!--
      shop-category-data provides the item data for a given category and item name.
    -->
<!--    <shop-category-data
        id="categoryData"
        category-name="[[routeData.category]]"
        item-name="[[routeData.item]]"
        item="{{item}}"
        failure="{{failure}}"></shop-category-data>-->
    <plugin-content-view visible="{{visible}}" contents="{{layout.product_detail_top}}" width="[[pageWidth]]"></plugin-content-view>
    <div id="content" hidden$="[[failure]]">
        <div class="medias">
            <plugin-scroll-box id="album" style="width:100%" scale-height="1.0"></plugin-scroll-box>
            <paper-icon-button on-click="_openVideo" hidden="[[!product.result.video]]" icon="videocam"></paper-icon-button>
        </div>
        
      <div class="detail" has-content$="[[_isDefined(item)]]">
        <h1>[[item.title]]</h1>
        <div class="price">
            <template is="dom-if" if="[[item.market_price]]">促销价：</template>
            [[_formatPrice(item.price)]]
            <template is="dom-if" if="[[item.market_price]]">
                ，原价：<s>[[_formatPrice(item.market_price)]]</s>
            </template>
            <template is="dom-if" if="[[onetoone]]">
                ，最低幸运价：<span style="color: green">[[_formatPrice(onetoone.price)]]</span>
            </template>
          </div>
        <div class="pickers">
            <template is="dom-repeat" items="[[skus]]" as="sku">
                <template is="dom-if" if="[[!_equal(sku.name,'id')]]">
                    <div class="sku-option" style$="{{_checkHidden(sku)}}">
                        <label>[[sku.label]]</label>
                        <paper-listbox on-selected-changed="_skuChanged" selected="[[_selectSkuDefault(sku)]]" attr-for-selected="value">
                            <template is="dom-repeat" items="[[sku.values]]" as="value">
                                <paper-item value="[[value]]">[[value]]</paper-item>
                            </template>
                        </paper-listbox>
                    </div>
                </template>
            </template>
            <template is="dom-if" if="{{_equal(product.result.type,'goods')}}">
                <template is="dom-if" if="{{_isEmpty(quantityList)}}">
                    <p>已售罄</p>
                </template>
            </template>
            <div hidden="{{_equal(product.result.type,'service')}}">
                <shop-select style="width:100%" hidden="{{_isEmpty(quantityList)}}">
                    <label id="quantityLabel" prefix>数量</label>
                    <select id="quantitySelect" aria-labelledby="quantityLabel">
                            <template is="dom-repeat" items="[[quantityList]]" as="quantity">
                                <option value="[[quantity]]">[[quantity]]</option>
                            </template>
                        </select>
                    <shop-md-decorator aria-hidden="true">
                        <shop-underline></shop-underline>
                    </shop-md-decorator>
                </shop-select>
            </div>
    </div>
    <div class="description">
        <plugin-content-view visible="{{visible}}" context="{{context}}" contents="[[contents]]" width="[[pageWidth]]"></plugin-content-view>
    </div>
    <template is="dom-if" if="{{_equal(product.result.type,'goods')}}">
        <div hidden="{{!bar_action_visible}}" >
            <div class="action" hidden="{{_isEmpty(quantityList)}}">
                <shop-button responsive>
                    <button hidden="{{!button_cart_visible}}" on-click="_addToCart" aria-label="添加此商品到购物车">添加到购物车</button>
                </shop-button>
                <shop-button responsive>
                    <button hidden="{{!button_buy_visible}}" on-click="_singleCheckout" aria-label="立即购买">立即购买</button>
                </shop-button>
            </div>
        </div>
    </template>
    <template is="dom-if" if="{{_equal(product.result.type,'service')}}">
        <div hidden="{{!bar_action_visible}}" class="action">
            <shop-button responsive>
                <button hidden="{{!button_buy_visible}}" on-click="_singleCheckout" aria-label="立即预约">立即预约</button>
            </shop-button>
        </div>
    </template>
    </div>
    </div>
    <plugin-content-view visible="{{visible}}" contents="{{layout.product_detail_bottom}}" width="[[pageWidth]]"></plugin-content-view>
    <div class="plugins">
        <div class="warp">
        <template is="dom-repeat" items="[[plugins]]" as="plugin">
            <div class="plugin" on-click="_openPlugin">
            <img src="[[plugin.config.icon]]"/>
            <span>[[plugin.display_name]]</span>
            </div>
        </template>
        </div>
    </div>
    </template>

    <script>
        class ShopProductDetail extends PluginElement {

            static get is() {
                return 'shop-product-detail';
            }

            static get properties() {
                return {

                    item: {
                        type:Object,
                        notify:true,
                        observer:"_itemChnaged"
                    },

                    route: Object,

                    routeData: Object,

                    visible: {
                        type: Boolean,
                        observer:"_visibleChanged"
                    },

                    failure: Boolean,
                    skus: Array,
                    skuGrid: Array,
                    contents: Array,
                    skuMapping: {
                        type: Object,
                        value: {
                            color: "颜色",
                            size:"尺码",
                            area:"面积",
                            volume:"体积",
                            capacity:"容量",
                            height:"高度",
                            width:"宽度",
                            length:"长度",
                            shape:"形状",
                            materials:"质地",
                            packing:"包装",
                            flavor:"风味",
                            type:"类型",
                            grade:"等级",
                            edition:"版本",
                            model:"型号",
                            specification:"规格",
                            common:"规格"
                        }
                    },
                    skuSelected: Object,
                    quantityList: Array,
                    onetoone:Object,
                    button_buy_visible:{value:true},
                    button_cart_visible:{value:true},
                    bar_action_visible:{value:true},
                    context:{value:{}}
                }
            }
            ready(){
                super.ready();
                this.context.root = this;
            }
            _customModelClick(e){
                if(e.detail.type=="product"){
                    let item = app.$.categoryData.getItem(e.detail.id);
                    app.route = {path:this.rootPath+"detail/"+item.category+"/"+item.name,prefix:""};
                }else if(e.detail.type=="blog"){
                    app.route = {path:this.rootPath+"blog/"+item.id,prefix:""};
                }else if(e.detail.type=="plugin"){
                    app.route = {path:this.rootPath+"plugin"+e.detail.link,prefix:""};
//                    this.$.xhr_open_page.setBody({page:app.httpHost+e.detail.link+"?app_id="+app.appId}).post();
                }
                
            }
            _checkHidden(sku){
                return sku.name=="common"?"display:none":null;
            }
            _itemChnaged(item){
                this.$.quantitySelect.value = '1';
                wx.miniProgram.postMessage({data:{pageURL:window.location.href,share:{title:item.title,imageUrl:item.defauleImage,sid:String(item.name),url:document.querySelector("base").href+"?app_id="+app.appId+"&scene="+encodeURIComponent(JSON.stringify({action:"openItem",productId:item.name}))}}});

                this.$.xhr_plugin_list_by_category_point.param("plugin_category","sale").param("plugin_point","%shop-detail-float%").param("app_id",app.appId).param("product_id",item.name).get();
                this.$.xhr_promotion_onetoone_get.param("product_id",item.name).callback((res)=>{
                    let result = res.detail.result;
                    if(result&&result.length>0){
                        let p = result[0];
                        let expire = this._date(p.createtime+p.expire_second*1000,"yyyy年MM月dd日HH点mm分");
                        if(p.price==0){
                            this.$.msg._message("恭喜！您可以免费领取此商品，请尽快下单！");
                        }else{
                            this.$.msg._message("恭喜！您购买此商品最低幸运价"+this._money(p.price)+"元，请尽快下单！");
                        }
                        this.onetoone = p;
                    }else{
                        this.onetoone = false;
                    }
                }).get();
                

                let skuRequest = new XMLHttpRequest();
                skuRequest.withCredentials = true;
                skuRequest.addEventListener("load", e=>{
                    this.skuSelected = new Object();
                    let skuMapping = new Object();
                    this.skuGrid = JSON.parse(e.target.responseText).result;
                    for (let i = 0; i < this.skuGrid.length; i++) {
                        let sku = this.skuGrid[i];
                        for (let n in sku) {
                            if (n=="id"||(this.skuMapping[n] && sku[n])) {
                                if (skuMapping[n]&&skuMapping[n].values.indexOf(sku[n])==-1) {
                                    skuMapping[n].values.push(sku[n]);
                                } else if(!skuMapping[n]){
                                    skuMapping[n] = {
                                        label: this.skuMapping[n],
                                        name: n,
                                        values: [sku[n]]
                                    };
                                }
                            }
                        }
                    }
                    let tempSkus = new Array();
                    for (let n in skuMapping) {
                        tempSkus.push(skuMapping[n]);
                    }
                    this.skus = tempSkus;
                    this._skuChanged();
                });
                skuRequest.open("GET", app.apiHost + "/product.sku.list?product_id=" + item.name + "&app_id=" + app.appId);
                skuRequest.send();
            }
            _visibleChanged(visible) {
                app.$.customerService.className = visible?"action":"";
                this.skus = new Array();
                if (visible) {
                    
                    this.$.xhr_product.param("product_id",this.routeData.product_id).param("app_id",app.appId).callback(res=>{
                        let product = res.detail.result;
                        this.context.product = product;
                        this.contents = product.content;
                        this.$.album.innerHTML = "";
                        let pics = new Array();
                        product.album.forEach(pic=>{
                            if(pic){
                                pics.push(pic);
                                let img = document.createElement("img");
                                img.src = pic;
                                img.className = "item";
                                img.addEventListener("click",()=>{
                                    this._viewImage(img.src,pics);
                                });
                                this.$.album.appendChild(img);
                            }
                        });
                        this.$.album.update();
                        this.item = {name:String(product.id),title:product.name,category:String(product.category_id),price:product.salemoney,market_price:product.market_price,description:product.name,image:this._albumItem(product.album,0,300,300),largeImage:this._albumItem(product.album,0,750,750),defauleImage:product.album[0],amount:product.amount,express_available:product.express_available,type:product.type,doorstep_service:product.doorstep_service};
                        this.dispatchEvent(new CustomEvent('change-section', {
                            bubbles: true,
                            composed: true,
                            detail: {
                                category: this.item ? this.item.category : '',
                                title: this.item ? this.item.title : ''
                            }
                        }));
                    }).get();
                    
                }
            }
            _unescapeText(text) {
                let elem = document.createElement('textarea');
                elem.innerHTML = text;
                return elem.textContent;
            }

            _formatPrice(price) {
                return price||price===0 ? '￥' + price.toFixed(2) : '';
            }
            _singleCheckout(){
                app.singleItem = {
                            item: this.item,
                            quantity: parseInt(this.$.quantitySelect.value?this.$.quantitySelect.value:1, 10),
                            sku: this.skuSelected
                        };
                this._page(this.rootPath+"checkout?single=true");
            }
            _addToCart() {
                for(let i=0;i<this.skus.length;i++){
                    if(this.skus[i].name!="id"&&!this.skuSelected[this.skus[i].name]){
                        this.$.msg._error("请选择"+this.skus[i].label);
                        return;
                    }
                }
                if((!this.$.quantitySelect.value)||this.$.quantitySelect.value==0){
                   this.$.msg._error("请选择购买数量");
                }else{
                    this.dispatchEvent(new CustomEvent('add-cart-item', {
                        bubbles: true,
                        composed: true,
                        detail: {
                            item: this.item,
                            quantity: parseInt(this.$.quantitySelect.value, 10),
                            sku: this.skuSelected,
                            quantityList:this.quantityList
                        }
                    }));
                }
                
            }

            _isDefined(item) {
                return item != null;
            }
            _selectSkuDefault(sku){
                this._skuChanged({model:{sku:sku},detail:{value:sku.values[0]}});
                return sku.values[0];
            }
            _skuChanged(e) {
                let qList = new Array();
                if(this.skuGrid.length==1&&this.skuGrid[0].common=="普通"){
                    for (let i = 0; i < this.skuGrid[0].amount; i++) {
                        qList.push(i + 1);
                        if (i == 100) {
                            break;
                        }
                    }
                }
                if(e){
                   let name = e.model.sku.name;
                    let value = e.detail.value;
                    this.skuSelected[name] = value;
//                    this.skuSelected.id = e.currentTarget.skuid;
                }
                let skuGridCopy = JSON.parse(JSON.stringify(this.skuGrid));
                for (let i = 0; i < skuGridCopy.length; i++) {
                    let removeable = false;
                    for (let n in this.skuSelected) {
                        if (n!="id"&&n!="common"&&skuGridCopy[i][n] != this.skuSelected[n]) {
                            removeable = true;
                            break;
                        }
                    }
                    if (removeable) {
                        skuGridCopy.splice(i, 1);
                        i--;
                    }
                }
                
                if(skuGridCopy.length>0&&skuGridCopy[0].amount){
                    if(e){
                        this.skuSelected.id = skuGridCopy[0].id;  
                    }
                   for (let i = 0; i < skuGridCopy[0].amount; i++) {
                        qList.push(i + 1);
                        if (i == 100) {
                            break;
                        }
                    }
                }
                this.quantityList = qList;
            }
            _openVideo(e){
                this.$.videoContainer.open();
                this.$.video.src = this.product.result.video;
                this.$.video.play();
            }
            _closeVideo(e){
                this.$.video.pause();
            }
            _openPlugin(e){
                this.$.xhr_open_page.setBody({page:app.httpHost+"/"+e.model.plugin.id+".pl/"+e.model.plugin.config.point["shop-detail-float"]+"?product_id="+this.item.name+"&app_id="+app.appId}).post();
            }
        }

        customElements.define(ShopProductDetail.is, ShopProductDetail);

    </script>

</dom-module>
